package com.mina.server;


import com.mina.constant.Constants;
import com.mina.model.Message;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;

/**
 * 服务端
 */
public class Server {

    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    public static void main(String[] args) {


        // 1.创建 同步非阻塞（NIO）的 Socket 接收器
        SocketAcceptor acceptor = new NioSocketAcceptor();


        // 2.获取过滤器链
        getAndSetChainFilter(acceptor);


        // 4.设置服务端的消息处理器
        acceptor.setHandler(new MinaServerHandler());


        int port = 9999;
        try {
            // 5.绑定端口，启动服务器（不会阻塞，立即返回）
            InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
            acceptor.bind(inetSocketAddress);
        } catch (IOException e) {
            LOGGER.error("连接断开");
        }
        LOGGER.info("Mina Server Running, Listener on : "+port);

        Scanner input = new Scanner(System.in);
        CompletableFuture.runAsync(() -> {
            while (true) {
                // 写
                if (input.nextLine().equals("2")) {
                    Constants.session1.write(setMsg());
                }
            }
        });
    }

    public static Message setMsg() {
        Message msg = new Message();
        msg.setFrom("client");
        msg.setTo("server");
        msg.setInfo("Hello, nice to meet you.");
        msg.setType("send");
        return msg;
    }









    private static void getAndSetChainFilter(SocketAcceptor acceptor) {
        DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain();

        /* 3.设定过滤器规则，以对象为单位读取数据 */
        // 对象序列化格式工厂
        ObjectSerializationCodecFactory serializationCodecFactory = new ObjectSerializationCodecFactory();
        filterChain.addLast("logger", new LoggingFilter());
        filterChain.addLast("objectFilter", new ProtocolCodecFilter(serializationCodecFactory));
    }

}
